javascript: (function () {
	/*
		Bookmarklet author: Eike Meier
		Modded a lot by: Spockholm Mafia Tools, http://www.facebook.com/mafiatools
	*/
	var version = 'Operation-a-Nator v1.02 beta',
	content = document.getElementById('popup_fodder'),
	stopimg = '',
	bitly_username = 'bitly_username',
	bitly_apikey = 'bitly_apikey',
	missionscookie = '',
	missions = {},
	debug = false,
	shorthand = true;

	// createCookie from Vern's Toolkit http://vern.com/mwtools/
	function createCookie(name,value) {
		// expire 7 days from now
		var expires = new Date();
		expires.setDate(expires.getDate()+7);
		document.cookie = name+"="+value+";expires="+expires.toGMTString()+"; path=/";
	}

	// readCookie from Vern's Toolkit http://vern.com/mwtools/
	function readCookie(name) {
		var i,
			cookie,
			nameEQ = name+"=",
			cookieArray = document.cookie.split(";");
		for (i=0; i< cookieArray.length; i++) {
			cookie = cookieArray[i];
			while (cookie.charAt(0)==' ')
				cookie = cookie.substring(1,cookie.length);
			if (cookie.indexOf(nameEQ) == 0)
				return cookie.substring(nameEQ.length,cookie.length);
		}
		return null;
	}

	function read_settings() {
		var settings = readCookie('spock_missions');
		if (settings == null || settings == 'undefined') {
			settings = bitly_username+'|'+bitly_apikey+'|'+missionscookie;
			createCookie('spock_missions',settings);
		}
		var parameters = settings.split('|');
		if (parameters.length < 3) {
			settings = bitly_username+'|'+bitly_apikey+'|'+missionscookie;
			createCookie('spock_missions',settings);
			parameters = settings.split('|');
		}
		bitly_username = parameters[0];
		bitly_apikey = parameters[1];
		missionscookie = parameters[2];
		missions_in_cookie = parameters[2].split('-');
		//alert(missions.length);
		for (i=0;i<missions_in_cookie.length;i++) {
			if(mission = /([a-f0-9]+)\s(\d+)\s(.*)/.exec(missions_in_cookie[i])) {
				missions[mission[1]] = new Array;
				missions[mission[1]].timestamp = mission[2];
				missions[mission[1]].tinyurl = mission[3];
				//alert(mission[i]+' '+mission[i][0]);
			}
		}
	}
	
	function write_settings() {
		bitly_username = document.getElementById('bitly_username').value;
		bitly_apikey = document.getElementById('bitly_apikey').value;
		var settings = bitly_username+'|'+bitly_apikey+'|'+missionscookie;
		createCookie('spock_missions',settings);
	}
	read_settings();	

	var config_html =
		'<style type="text/css">'+
		'.messages img{margin:0 3px;vertical-align:top};'+
		'#close{display:inline};'+
		'</style>'+
		'<table class="messages" border="0">'+
			'<tr><td align="left" style="text-align:lef;font-size:0.9em;"><a href="#" id="loadmissions">Load Operations</a></td><td align="left" style="text-align:lef;font-size:0.9em;"><a href="#" id="cleancookie">Clean Cookie ('+(missions_in_cookie.length-1)+')</a></td><td align="right" style="text-align:right;font-size:1.1em;">'+version+' - <a href="http://www.spockholm.com/mafia/bookmarklets.php" target="_top">Spockholm Mafia Tools</a> - <a href="http://www.spockholm.com/mafia/donate.php?Mission-a-Nator" alt="Buy Spockholm a beer" target="_blank">Donate</a> - <a href="#" id="close"><img src="'+stopimg+'" title="Close" alt="Close" width="16" height="16"></a></td></tr>' +
			'<tr><td colspan="3"><hr /></td></tr>'+
			'<tr><td>Status:</td><td colspan="2" id="spock_status">Loaded operations, press buttons to make TinyURLs</td></tr>'+
			'<tr><td>Select Service:</td><td colspan="2">'+
				'<form id="service_select">'+
				'<label><input type="radio" name="service_selected" value="tinyurl1" checked="checked">Public Tiny</label>'+
				'<label><input type="radio" name="service_selected" value="tinyurl2">Spockholm Tiny</label>'+
				'<label><input type="radio" name="service_selected" value="bitly">bit.ly</label>'+
				'&nbsp; &nbsp;<span id="service_info" class="energy_highlight">Public TinyURL service, can hit quota limits.</span></form>'+
			'</td></tr>'+
			'<tr id="bitly_row" style="display:none;">'+
				'<td>bit.ly info:</td>'+
				'<td colspan="2">Username:<input id="bitly_username" type="text" value="'+bitly_username+'"> API key:<input id="bitly_apikey" type="text" value="'+bitly_apikey+'"> (<a href="http://bit.ly/a/your_api_key">Get key here</a>)</td>'+
			'</tr>'+
			'<tr><td colspan="3"><hr /></td></tr>'+
			'<tr valign="top"><td>Operations:</td><td colspan="3">'+
				//'<table id="missions" width="100%" border="0"><tr valign="top"><th>Owner</th><th>Name</th><th>Level</th><th>Time</th><th>Slots</th><th>TinyURL</th></tr></table>'+
				'<table id="missions" width="100%" border="0"><tr valign="top"><th>Name</th><th>Level</th><th>Time</th><th>Slots</th><th>TinyURL</th></tr></table>'+
			'</td></tr>'+
			'<tr id="text_row">'+
				'<td valign="top">Text Links:</td>'+
				'<td colspan="2"><textarea id="text_list" class="instructions" rows="10" cols="75"></textarea></td>'+
			'</tr>'+
			'<tr id="short_row"">'+
				'<td valign="top">Short Text:</td>'+
				'<td colspan="2"><textarea id="short_list" class="instructions" rows="10" cols="75"></textarea></td>'+
			'</tr>'+
			'<tr id="forum_row"">'+
				'<td valign="top">Forum Links:</td>'+
				'<td colspan="2"><textarea id="forum_list" class="instructions" rows="10" cols="75"></textarea></td>'+
			'</tr>'+
			'<tr><td></td><td colspan="2"><span class="more_in">We are testing a few different ways to output the data, <a href="http://www.facebook.com/topic.php?uid=92178514356&topic=24118">discuss here</a>.</span></td></tr>'+
		'</table>';
	
	function create_div() {
		if (document.getElementById('spockdiv')) {
			document.getElementById('spockdiv').innerHTML = config_html;
		}
		else {
			var spock_div = document.createElement("div");
			spock_div.id = 'spockdiv';
			spock_div.innerHTML = config_html;
			content.insertBefore(spock_div, content.firstChild);
		}
	}
	
	create_div();
	
	document.getElementById('close').onclick = function(e) {
		content.removeChild(document.getElementById('spockdiv'));
		return false;
	};
	
	document.getElementById('loadmissions').onclick = load_missions;
	document.getElementById('cleancookie').onclick = function(e) {
		msg('Removed all operations from the cookie. No cookie for you!');
		missionscookie = '';
		write_settings();
		return false;
	};

	document.getElementById('service_select').onchange = function () {
		if($("input[name='service_selected']:checked").val() == 'bitly') {
			$('#bitly_row').show();
			$('#service_info').html('Using your own account features click tracking.');
			bitly_username = document.getElementById('bitly_username').value;
			bitly_apikey = document.getElementById('bitly_apikey').value;
			write_settings();
		}
		if($("input[name='service_selected']:checked").val() == 'tinyurl1') {
			$('#bitly_row').hide();
			$('#service_info').html('Public TinyURL service, can hit quota limits.');
		}
		if($("input[name='service_selected']:checked").val() == 'tinyurl2') {
			$('#bitly_row').hide();
			$('#service_info').html('Spockholm TinyURL service, can be overloaded.');
		}
		if($("input[name='service_selected']:checked").val() == 'none') {
			$('#bitly_row').hide();
			$('#service_info').html('Do not make short urls, only long.');
		}
		//return false;
	};
	document.getElementById('bitly_username').onkeyup = function () {
		write_settings();
	};
	document.getElementById('bitly_apikey').onkeyup = function () {
		write_settings();
	};
	function msg(s) {
		document.getElementById('spock_status').innerHTML = s;
	}
	
	function write_textfields(mid) {
		document.getElementById('text_list').value += missions[mid].name+' ('+missions[mid].difficulty+') Slots Free: '+missions[mid].slots+' Time:'+missions[mid].time+' Link: '+missions[mid].tinyurl+'\n';
		document.getElementById('short_list').value += missions[mid].name+' ('+missions[mid].difficulty.substr(0,1)+') '+missions[mid].slots+' by '+missions[mid].owner+' ['+missions[mid].tinyurl+']\n';
		document.getElementById('forum_list').value += '[url='+missions[mid].tinyurl + ']'+missions[mid].name+' ('+missions[mid].difficulty+')[/url] Slots Free: '+missions[mid].slots+' Time:'+missions[mid].time+'\n';
	}
	
	function load_missions() {
		var b = document.getElementsByClassName('socialMission');
		if (b.length < 1) { 
			do_ajax('inner_page','remote/html_server.php?xw_controller=socialmission&xw_action=view&xw_city=&tmp=&xw_person=&type=helper',1,1,0,0);
			return;
		}
		for (i = 0; i < b.length; i++) {
			var mid = b[i].id.substring(14);
			//console.log(typeof missions[mid]);
			//console.log('missions[mid] is: '+typeof missions[mid]);
			if (b[i].getElementsByClassName('missionLeader').length > 0) { //my mafia mission
				//console.log('mission.length: '+b[i].getElementsByClassName('missionLeader').length);
				var m = /socialMission_[\d\w]+_(\d+)/.exec(b[i].getElementsByClassName('missionLeader')[0].innerHTML);
				var uid = m[1];
				var owner = />\"(.*?)\"</.exec(b[i].getElementsByClassName('missionLeader')[0].innerHTML)[1].replace(/\\\\"/g,'');
			}
			else { //it is a personal mission
				var userid = /sf_xw_user_id=([a-z]\|[0-9]+)/.exec(document.body.innerHTML)[1];
				var uid = /([a-z]\|([0-9]+))/.exec(userid)[2];
				var owner = 'Me';
			}
			var mid = b[i].id.substring(14);
			var link = 'http://apps.facebook.com/inthemafia/track.php?next_controller=socialmission&next_action=joinMission&zy_track=feed&sendkey=a&sendtime=&friend=p%7C' + uid + '&next_params=%7B%22owner_id%22%3A%22p%7C'+uid+'%22%2C%22feed_key%22%3A%221%22%2C%22instance_id%22%3A%22'+mid+'%22%2C%22mission_num%22%3A%225%22%7D&ref=nf';
			var name = b[i].getElementsByClassName('missionName')[0].innerHTML.replace(/^\s+|\s+$/g,'');
			var difficulty = b[i].getElementsByClassName('missionDifficulty')[0].innerHTML.replace(/<[^<]+?>/g,'');
			var time = b[i].getElementsByClassName('missionTimeText')[0].innerHTML.replace(/TIME REMAINING:/,'');
			var freeslots = 0;
			var missionslots = b[i].getElementsByClassName('missionTasks')[0].getElementsByClassName('missionTaskBox').length;
			for (j = 0; j<missionslots;j++) {
				if(/silhoutte/.test(b[i].getElementsByClassName('missionTasks')[0].getElementsByClassName('missionTaskImage')[j].style.background)) {
					freeslots++;
				}
			}
			var newitem = '';
			if (typeof missions[mid] == 'undefined') { //mission is not listed in the cookie
				missions[mid] = new Array;
				missions[mid].name = name;
				missions[mid].owner = owner;
				missions[mid].url = link;
				missions[mid].difficulty = difficulty;
				missions[mid].slots = freeslots+'/'+missionslots;
				missions[mid].time = time.replace(/<[^<]+?>/g,'');
				//console.log('missions[mid] was not in the cookie, type: '+typeof missions[mid]);
				//newitem = '<tr><td>'+owner+'</td><td><a href="'+link+'">'+name+'</a></td><td>'+difficulty+'</td><td>'+time+'</td><td>'+freeslots+'/'+missionslots+'</td><td><a href="#" id="'+mid+'">Make Tinyurl</a></td></tr>';
				newitem = '<tr><td><a href="'+link+'">'+name+'</a></td><td>'+difficulty+'</td><td>'+time+'</td><td>'+freeslots+'/'+missionslots+'</td><td><a href="#" id="'+mid+'">Make Tinyurl</a></td></tr>';
				$('#missions').append(newitem);
				$('#'+mid).click(function() { makeTinyUrl(this.id); });
			}
			else { //mission is in the cookie
				//console.log('missions[mid] is in cookie, type: '+typeof missions[mid]);
				missions[mid].name = name;
				missions[mid].owner = owner;
				missions[mid].url = link;
				missions[mid].difficulty = difficulty;
				missions[mid].slots = freeslots+'/'+missionslots;
				missions[mid].time = time.replace(/<[^<]+?>/g,'');
				if (document.getElementById(mid) == null) {
					//console.log('elementID matched null: '+document.getElementById(mid));
					//newitem = '<tr><td><a href="'+link+'">'+name+'</a></td><td>'+difficulty+'</td><td>'+time+'</td><td>'+freeslots+'/'+missionslots+'</td><td id="'+mid+'"><a href="'+missions[mid].tinyurl+'" id="'+mid+'">TinyURL</a> <span class="more_in">(from cookie)</span>'+missions[mid].timestamp+'</td></tr>';
					//newitem = '<tr><td>'+owner+'</td><td><a href="'+link+'">'+name+'</a></td><td>'+difficulty+'</td><td>'+time+'</td><td>'+freeslots+'/'+missionslots+'</td><td><a href="'+missions[mid].tinyurl+'" id="'+mid+'">TinyURL</a> <span class="more_in">(from cookie)</span></td></tr>';
					newitem = '<tr><td><a href="'+link+'">'+name+'</a></td><td>'+difficulty+'</td><td>'+time+'</td><td>'+freeslots+'/'+missionslots+'</td><td><a href="'+missions[mid].tinyurl+'" id="'+mid+'">TinyURL</a> <span class="more_in">(from cookie)</span></td></tr>';
					$('#missions').append(newitem);
					if (typeof missions[mid].tinyurl != 'undefined') {
						write_textfields(mid);
					}
				}
				else {
					if (debug) { console.log(mid+' elementid did exist: '+document.getElementById(mid)); }
				}
			}
		}
	}
	
	function makeTinyUrl(mid) {
		var name = missions[mid].name;
		var url = missions[mid].url;
		var difficulty = missions[mid].difficulty;
		//alert(mid+name+url+difficulty);
		if ($("input[name='service_selected']:checked").val() == 'tinyurl1') {
			msg('Making tinyurl1 for operation: '+name);
			$.getJSON("http://json-tinyurl.appspot.com/?&callback=?",
			{url: url},
			function (data) {
				if (data.error) {
					msg('<span class="bad">'+data.error+'</span> Select another service or try again.');
					//document.getElementById('text_list').value += name+': '+data.error+'\n';
				}
				else {
					msg('Made tinyurl1 for operation: '+name);
					//document.getElementById(mid).innerHTML = '<a href="'+data.tinyurl+'">'+name+'</a>';
					document.getElementById(mid).innerHTML = '<a href="'+data.tinyurl+'">TinyURL</a>';
					missions[mid].tinyurl = data.tinyurl;
					var timestamp = Math.round(new Date().getTime() / 1000);
					missionscookie += mid+' '+timestamp+' '+data.tinyurl+'-';
					//if (debug) { console.log(missionscookie += mid+' '+timestamp+' '+data.tinyurl+'-'); }
					//missions[mid].timestamp = timestamp;
					write_settings();
					write_textfields(mid);
				}
			});
		}
		if ($("input[name='service_selected']:checked").val() == 'tinyurl2') {
			msg('Making tinyurl2 for operation: '+name);
			$.getJSON("http://www.exellerate.com/mafia/urlshortner/multiple-url-shortener.php?callback=?",
			{url: url},
			function(data){
				msg('Made tinyurl2 for operation: '+name);
				document.getElementById(mid).innerHTML = '<a href="'+data.tinyurl+'">TinyURL</a>';
				missions[mid].tinyurl = data.tinyurl;
				var timestamp = Math.round(new Date().getTime() / 1000);
				missionscookie += mid+' '+timestamp+' '+data.tinyurl+'-';
				write_settings();
				write_textfields(mid);
				//document.getElementById('tiny_gift_list').value += itemname +': '+data.tinyurl + '\n';
			});
		}
		if ($("input[name='service_selected']:checked").val() == 'bitly') {
			msg('Making bit.ly for operation: '+name);
			$.getJSON("http://api.bit.ly/v3/shorten?login="+bitly_username+"&apiKey="+bitly_apikey+"&longUrl=" + escape(url) + "&format=json&callback=?",
			function(data){
				msg('Made bit.ly for operation: '+name);
				document.getElementById(mid).innerHTML = '<a href="'+data.data.url+'">TinyURL</a>';
				missions[mid].tinyurl = data.data.url;
				var timestamp = Math.round(new Date().getTime() / 1000);
				missionscookie += mid+' '+timestamp+' '+data.data.url+'-';
				write_settings();
				write_textfields(mid);
			});
		}
	}
	
	load_missions();
	
	//testing to add analytics
	function loadContent(file){
		var head = document.getElementsByTagName('head').item(0)
		var scriptTag = document.getElementById('loadScript');
		if(scriptTag) head.removeChild(scriptTag);
			script = document.createElement('script');
			script.src = file;
			script.type = 'text/javascript';
			script.id = 'loadScript';
			head.appendChild(script);
	}
	loadContent('http://www.google-analytics.com/ga.js');
	try {
		var pageTracker = _gat._getTracker("UA-8435065-3");
		pageTracker._trackPageview();
		pageTracker._trackPageview("/script/Operation-a-Nator"); 
	} catch(err) {}
	
})()
